<template>
  <div >
    <el-breadcrumb separator="/">
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="card-box">
      <div class="func-box">
        <el-input placeholder="请输入内容" v-model="query" class="search"
          clearable
          @keyup.enter.native="getUserList"
        >
          <el-button slot="append" icon="el-icon-search"
            @click="getUserList"
          ></el-button>
        </el-input>
        <el-button type="primary" 
          @click="addDialogVisable = true"
        >添加用户</el-button>
      </div>
      <el-table
        :data="tableData"
        border
        style="width: 100%">
        <el-table-column
          type="index"
          label="序号"
          width="50">
        </el-table-column>
        <el-table-column
          prop="username"
          label="用户名"
          width="150">
        </el-table-column>
        <el-table-column
          prop="email"
          label="邮箱"
          width="180">
        </el-table-column>
        <el-table-column
          prop="mobile"
          label="电话">
        </el-table-column>
          <el-table-column
          prop="role_name"
          label="角色">
        </el-table-column>
        <el-table-column label="状态" width="80">
          <template v-slot="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              @change="handleStateChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template v-slot="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit"
              @click="showEditDialog(scope.row)"
            ></el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete"
              @click="handleDeleteUser(scope.row.id)"
            ></el-button>
            <el-tooltip effect="dark" content="分配角色" placement="top-start">
              <el-button size="mini" type="warning" icon="el-icon-setting"
                @click="handleRoleDialogOpen(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pagenum"
      :page-sizes="[8, 16, 24, 40]"
      :page-size="8"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
    <!-- 添加用户弹框 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisable"  @closed="handleAddDialClose">
      <el-form  label-width="80px"
      :model="addUserForm" :rules="userRules" ref="addFormRef"
      >
        <el-form-item label="用户名" prop="username" required>
          <el-input v-model="addUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" required>
          <el-input v-model="addUserForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisable = false">取 消</el-button>
        <el-button type="primary" @click="confirmAddDialog">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 编辑用户弹框 -->
     <el-dialog title="编辑用户" :visible.sync="editDialogVisable" @closed="handleEditDialClose">
      <el-form  label-width="80px"
      :model="editUserForm" :rules="userRules" ref="editFormRef"
      >
        <el-form-item label="用户名" prop="username" >
          <el-input v-model="editUserForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisable = false">取 消</el-button>
        <el-button type="primary" @click="confirmEditDialog">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 分配角色弹框 -->
    <el-dialog title="分配角色" :visible.sync="roleDialogVisable">
      <div style="margin-bottom:20px">
        <span>用户：</span> <span>{{roleUser.username}}</span>
      </div>
      <span>角色：</span>
      <el-select v-model="roleUser.rid" :placeholder="roleUser.roleName">
        <el-option v-for="item in roleList" :key="item.id"
         :value="item.id" :label="item.roleName"></el-option>
      </el-select>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelUpdateUserRole">取 消</el-button>
        <el-button type="primary" @click="confirmUpdateUserRole">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {getRoles} from '../../api/role'
import {
  getUsers, 
  updateUserState, 
  addUser,
  updateUser,
  deleteUser,
  updateUserRole
} from '../../api/user'
import {
  checkUsername,
  checkPassword,
  checkPhone,
  checkEmail
} from '../../utils/validate'
const CommRoleUser = {
  id:-1,
  rid:'',
  username:'',
  roleName:''
}
export default {
  created(){
    this.getUserList()
  },
  data(){
    return {
      query:'',
      pagenum:1,
      pagesize:8,
      total:0,
      tableData:[],
      addDialogVisable:false,
      editDialogVisable:false,
      roleDialogVisable:false,
      addUserForm:{
        username:'',
        password:'',
        email:'',
        mobile:'',
      },
      editUserForm:{
        username:'',
        email:'',
        mobile:'',
      },
      userRules:{
        username:[
          { validator: checkUsername, trigger: 'blur' }
        ],
        password:[
          { validator: checkPassword, trigger: 'blur' }
        ],
        mobile:[
          { validator: checkPhone, trigger: 'blur' }
        ],
        email:[
          { validator: checkEmail, trigger: 'blur' }
        ],
      },
      // 选择角色
      roleUser:Object.assign({},CommRoleUser),
      roleList:[]
    }
  },
  methods:{
    // 获取用户信息
    async getUserList(){
      try {
        const res = await getUsers({
          query:this.query,
          pagenum:this.pagenum,
          pagesize:this.pagesize,
        })
        this.tableData=res.data.users
        this.total = res.data.total
      } catch (err) {
        console.log(err);
      }
    },
    // 修改用户状态
    handleStateChange(row){
       this.$confirm(`确认修改`,'修改',{
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(()=>{
        this.changeMsgState(row)
      }).catch(()=>{
        row.mg_state = !row.mg_state
        this.$message({
          message:'取消修改',
          type:'info'
        })
      })
    },
    async changeMsgState (row){
      try {
        const res = await updateUserState({
          uId:row.id,
          type:row.mg_state
        })
        //修改成功
        if(res.meta.status === 200){
          this.$message({
            message:res.meta.msg,
            type:'success'
          })
        }
        
      } catch (err) {
        // 修改失败
        row.mg_state = !row.mg_state
      }
    },
    // 分页大小改变
    /*这里可以不用判断size是否变化，因为elementui中若size,num没有变则不会发生回调*/
    handleSizeChange(size){
      if(this.pagesize!==size){ //判断size是否变化，重新拉取数据
        this.pagenum = 1
        this.pagesize = size
        this.getUserList()
      }
    },
    // 页码改变
    handleCurrentChange(num){
      if(this.pagenum!==num){ //重新拉取数据
        this.pagenum = num
        this.getUserList()
      }
    },
     // 显示编辑用户窗口
    showEditDialog (row){
      this.editDialogVisable = true
      console.log(row);
      this.editUserForm.id = row.id
      this.editUserForm.username = row.username
      this.editUserForm.email = row.email
      this.editUserForm.mobile = row.mobile
    },
    // 处理添加框和编辑框关闭
    handleAddDialClose(){
      this.$refs.addFormRef.resetFields()
    },
    handleEditDialClose(){
      this.$refs.editFormRef.resetFields()
    },
    // 确认添加
    confirmAddDialog(){
      this.$refs.addFormRef.validate(async v=>{
        if(v){//验证通过
          try {
            const res = await addUser(this.addUserForm)
            this.$message({
              message:res.meta.msg,
              type:'success'
            })
            this.addDialogVisable = false
           
            // 让新增数据显示在第一行
            this.tableData = [res.data, ...this.tableData]
          } catch (err) {
            console.log(err);
          }
        }else{//验证不通过
          this.$message({
            message:'请正确填写信息',
            type:'warning'
          })
        }
      })
    },
 
    // 确认编辑提交
    confirmEditDialog(){
      this.$refs.editFormRef.validate(async (v)=>{
        if(v){ //验证通过
          try {
            const res = await updateUser(this.editUserForm.id,
            {
              email:this.editUserForm.email,
              mobile:this.editUserForm.mobile
            })
            // 修改成功
            this.$message({
              message:res.meta.msg,
              type:'success'
            })
            this.editDialogVisable = false
            this.getUserList()
          } catch (err) {
            console.log(err);
          }
        }else{//验证不通过
          this.$message({
            message:'请正确填写信息',
            type:'warning'
          })
        }
      })
    },
    // 删除用户
    handleDeleteUser(id){
      this.$confirm('此操作将永久删除该用户信息, 是否继续?','删除用户',{
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async ()=>{
        //请求删除
        try {
          const res = await deleteUser(id)
          // 删除成功
          this.$message({
            message:res.meta.msg,
            type:'success'
          })
          this.getUserList()
        } catch (err) {
          console.log(err);
        }
      }).catch(()=>{
        this.$message({
          message:'取消删除',
          type:'info'
        })
      })
    },
    // 打开分配角色弹框
    async handleRoleDialogOpen(user){
      console.log(user);
      this.roleDialogVisable = true
      this.roleUser = {
        id : user.id,
        rid : '',
        username : user.username,
        roleName : user.role_name
      }
      // 获取角色列表
      try {
        const res = await getRoles()
        this.roleList = res.data
      } catch (err) {
        console.log(err);
      }
    },
    // 取消修改用户角色
    cancelUpdateUserRole(){
      this.roleDialogVisable = false
      this.roleUser = Object.assign({},CommRoleUser)
    },
    // 确认修改用户角色
    async confirmUpdateUserRole(){
      if(this.roleUser.rid == ''){
        this.$message('请重新选择角色再确认！')
      }else{
        try {
          const res = await updateUserRole(this.roleUser.id,{
            rid:this.roleUser.rid
          })
          this.$message({
            type:'success',
            message:res.meta.msg
          })
          this.roleDialogVisable = false,
          this.roleUser = Object.assign({},CommRoleUser)
        } catch (err) {
          console.log(err);
        }
      }
    }

  }
}
</script>
<style scoped>

.func-box{
  margin-bottom: 20px;
}
.search{
  min-width: 300px;
  max-width: 400px;
  margin-right: 20px;
}


</style>